<script setup lang="ts">
import {onMounted, ref} from "vue"
import {BaseDirectory, resolveResource} from "@tauri-apps/api/path";
import {Child, Command} from "@tauri-apps/plugin-shell";
import {writeTextFile} from '@tauri-apps/plugin-fs';
import {eol} from '@tauri-apps/plugin-os';
import {ElMessage} from "element-plus";
import {DATABASE_PATH} from "../constant/ConfigConstant.ts";
import TOML from '@ltd/j-toml';
import Database from "@tauri-apps/plugin-sql";
import {Delete, Plus, Promotion, Refresh, RefreshLeft, Close} from "@element-plus/icons-vue";
// 在文件顶部添加导入
import {v4 as uuidv4} from 'uuid';
import {useSpawnPidStore} from "../stores/AppSpawn.ts";

const spawnPidStore = useSpawnPidStore()

const proxyTypeList = [
  {
    label: 'tcp',
    value: 'tcp'
  },
  {
    label: 'udp',
    value: 'udp'
  },
  {
    label: 'http',
    value: 'http'
  },
  {
    label: 'https',
    value: 'https'
  },
  {
    label: 'tcpmux',
    value: 'tcpmux',
  },
  {
    label: 'stcp',
    value: 'stcp',
  },
  {
    label: 'sudp',
    value: 'sudp',
  },
  {
    label: 'xtcp',
    value: 'xtcp',
  },
]


const tableName = 'frp_plugin_table';

// frp-client-config.ts
interface FrpClientConfig {
  serverAddr: string;// 服务器地址
  serverPort: number;// 服务器端口
  auth: {
    token: string;// 认证token
  };
  proxies: Array<{
    name: string;// 代理名称
    type: string;// 代理类型
    localIP: string;// 本地IP
    localPort: number;// 本地端口
    remotePort: number;// 远程端口
  }>;
}

const getEntity = ref<FrpPluginTableEntity>();

const loadFrpConfig = ref<FrpClientConfig>({
  serverAddr: '',
  serverPort: 7000,
  auth: {token: ''},
  proxies: []
});

interface FrpPluginTableEntity {
  id: number;// 主键
  client_config_type: string;// 客户端配置类型
  parent_id: number;// 父级id
  config_key: string;// 配置key
  config_value: string;
  local_port: string;// 本地端口
  remote_port: string;// 远程
}

const launchFrp = async () => {
  const pid = spawnPidStore.getSpawnPid('frpc');
  if (pid) {
    ElMessage.success('frp已经启动');
    return;
  }
  resolveResource('resources/frpc_launch.toml')
      .then(resourcePath => {
        Command.sidecar('binaries/frpc', [
          '-c',
          resourcePath,
        ]).spawn()
            .then(child => {
              spawnPidStore.updateSpawnPid(child.pid, 'frpc')
              ElMessage.success('frp启动成功');
            });
      });
}
// 保存配置
const saveConfig = async () => {
  resolveResource(DATABASE_PATH).then((resourcePath) => {
    Database.load('sqlite:' + resourcePath).then(db => {
      if (getEntity.value && loadFrpConfig.value) {
        const str = eol();
        //后续可以继续 添加其他配置
        let tomlConfig = `serverAddr="${loadFrpConfig.value.serverAddr}"${str}serverPort=${loadFrpConfig.value.serverPort}${str}[auth]${str}token="${loadFrpConfig.value.auth.token}"${str}`;
        loadFrpConfig.value.proxies.map((proxy) => {
          tomlConfig += `[[proxies]]${str}name = "${proxy.name}"${str}type = "${proxy.type}"${str}localIP = "${proxy.localIP}"${str}localPort = ${proxy.localPort}${str}remotePort = ${proxy.remotePort}${str}`;
        });
        // 取消注释以实际保存到数据库
        db.execute(`UPDATE ${tableName}
                    SET config_value = ?
                    WHERE id = ?`,
            [tomlConfig, getEntity.value?.id]).then((result) => {
          console.log(result);
        }).then(() => {
          ElMessage.success('保存成功');
        });
      }
    })
  })
}

const deleteConfig = (proxyName: string) => {
  if (!loadFrpConfig.value?.proxies) return
  // 创建新数组（符合 Vue 响应式要求）
  loadFrpConfig.value.proxies = loadFrpConfig.value.proxies.filter(
      proxy => proxy.name !== proxyName
  );
}

const stopFrp = () => {
  const pid = spawnPidStore.getSpawnPid('frpc');
  if (pid) {
    const frpcChild = new Child(pid);
    frpcChild.kill().then(() => {
      spawnPidStore.removeSpawnPid('frpc');
      ElMessage.success('frp已经停止');
    });
  }
}

const addEntityConfig = () => {
  if (!loadFrpConfig.value?.proxies) return
  loadFrpConfig.value.proxies.push({
    name: uuidv4(),
    type: 'tcp',
    localIP: '127.0.0.1',
    localPort: 8080,
    remotePort: 8080,
  })
}


onMounted(() => {
  // 加载数据库
  resolveResource(DATABASE_PATH).then((resourcePath) => {
    Database.load('sqlite:' + resourcePath).then(db => {
      //查询配置，写入配置文件中
      db.select<FrpPluginTableEntity[]>(`SELECT *
                                         FROM ${tableName}`)
          .then((result) => {
            const clientCommonConfig = result.find((item) => item.client_config_type === 'frp_client_config');
            getEntity.value = clientCommonConfig;
            if (clientCommonConfig) {
              const parsedConfig = TOML.parse(clientCommonConfig.config_value) as unknown;
              loadFrpConfig.value = validateConfig(parsedConfig);
              writeTextFile('resources/frpc_launch.toml', clientCommonConfig.config_value,
                  {baseDir: BaseDirectory.Resource});
            }
          })
    });
  });
});


// 在 validateConfig 中添加类型校验（当前是直接断言）
function validateConfig(config: unknown): FrpClientConfig {
  if (!config || typeof config !== 'object') throw new Error('Invalid config');
  // 这里可以添加更详细的属性校验
  return config as FrpClientConfig;
}

</script>

<template>
  <div style="width: 100%; height: 100%;
   display: flex; flex-direction: column;">
    <!-- 内容区域添加滚动 -->
    <div style="flex: 0 0 auto;margin-top: 10px;">Frp配置</div>
    <div style="display: flex;align-items: center; flex: 0 0 auto;margin-top: 10px;">
      <div>中转服务器地址:</div>
      <el-input v-model="loadFrpConfig.serverAddr" style="width: 150px"/>
    </div>
    <div style="flex: 1; overflow-y: auto; margin-top: 10px">
      <div style="flex: 1;gap: 10px;display: flex;flex-direction: column;">
        <div v-for="item in loadFrpConfig.proxies" :key="item.name" style="display: flex;height: 35px;gap: 20px">
          <div style="display: flex;justify-content: center;align-items: center">
            <div>远程端口</div>
            <el-input
                v-model="item.remotePort"
                style="width: 100px"
                :placeholder="item.remotePort"
            />
          </div>
          <div style="display: flex;justify-content: center;align-items: center">
            <div>本机端口</div>
            <el-input
                v-model="item.localPort"
                style="width: 100px"
                :placeholder="item.localPort"
            />
          </div>
          <el-select
              v-model="item.type"
              :placeholder="item.type"
              style="width: 80px"
          >
            <el-option
                v-for="item in proxyTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <el-button type="danger" @click="deleteConfig(item.name)" :icon="Delete"/>
        </div>
      </div>
    </div>

    <div style="flex: 0 0 auto; display: flex">
      <el-button @click="addEntityConfig" :icon="Plus">添加</el-button>
      <el-button @click="saveConfig" :icon="RefreshLeft">保存</el-button>
      <el-button @click="launchFrp" :icon="Promotion">启动</el-button>
      <el-button @click="saveConfig" :icon="Refresh">重启</el-button>
      <el-button @click="stopFrp" :icon="Close">停止</el-button>
    </div>
  </div>

</template>

<style scoped>
</style>